package com.zpself.module.算法练习.二叉树;

/**
 * @author By ZengPeng
 * @Description
 * @date in  2021/1/20 19:13
 * @Modified By
 */
public class 力扣_235_二叉搜索树的最近公共祖先 {
    public static void main(String[] args) {
        TreeNode treeNode = TreeNode.initRoot();
        TreeNode root_0 = new TreeNode(1);
        TreeNode root_l = new TreeNode(2);
        System.out.println(lowestCommonAncestor(treeNode,root_0,root_l));
    }

    public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q){
        if (root == null || root == p || root == q)    //如果根节点为空或者等于 p，或者等于q，则直接返回根节点
            return p;
        if (p.val > root.val && q.val > root.val) {
            return lowestCommonAncestor(root.right,p,q);
        }else if (p.val < root.val && q.val < root.val) {
            return lowestCommonAncestor(root.left,p,q);
        }else{
            return root;
        }
    }
}
